from PyQt5.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QStatusBar, QMessageBox
from PyQt5.QtCore import Qt, QTimer
from gui.controls import ControlPanel
from gui.viewer_3d import GLWidget
from simulator.drone_sim import DroneSimulator
import logging

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Drone Flight Controller v1.0")
        self.setGeometry(100, 100, 1400, 900)
        
        # 初始化日志系统
        self.logger = logging.getLogger("FlightCtrl")
        self.logger.setLevel(logging.INFO)
        handler = logging.StreamHandler()
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        
        # 创建组件
        self.viewer = GLWidget()
        self.controls = ControlPanel()
        self.simulator = DroneSimulator()
        
        # 设置布局
        main_layout = QHBoxLayout()
        main_layout.addWidget(self.viewer, 3)
        main_layout.addWidget(self.controls, 1)
        
        container = QWidget()
        container.setLayout(main_layout)
        self.setCentralWidget(container)
        
        # 状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_timer = QTimer()
        self.status_timer.timeout.connect(self.update_status)
        self.status_timer.start(500)  # 0.5秒更新间隔
        
        # 连接信号
        self.controls.control_signal.connect(self.simulator.set_control)
        self.simulator.pose_updated.connect(self.viewer.update_pose)
        self.simulator.status_updated.connect(self.update_status_bar)
        
        # 启动模拟器
        self.simulator.start()
        
        # 窗口关闭处理
        self.setAttribute(Qt.WA_DeleteOnClose)
        
    def update_status(self):
        """定时更新状态信息"""
        if self.simulator.is_running():
            self.status_bar.showMessage("Simulator Running")
        else:
            self.status_bar.showMessage("Simulator Stopped")
            
    def update_status_bar(self, message):
        """接收模拟器状态信息"""
        self.status_bar.showMessage(message, 3000)
        
    def closeEvent(self, event):
        """窗口关闭时的处理"""
        self.simulator.stop()
        self.logger.info("Main window closed")
        event.accept()